import { useState, useEffect } from 'react'
import { motion, AnimatePresence } from 'framer-motion'
import { formatDate } from '../services/storage'

interface Letter {
  id: number
  title: string
  date: string
  author: string
  content: string
  isHandwritten: boolean
}

interface LetterFormProps {
  isOpen: boolean
  onClose: () => void
  onSubmit: (letter: Letter | Omit<Letter, 'id'>) => void
  initialData?: Letter | null
}

export function LetterForm({ isOpen, onClose, onSubmit, initialData }: LetterFormProps) {
  const [formData, setFormData] = useState({
    title: '',
    content: '',
    author: '他',
    isHandwritten: false,
    date: formatDate().replace(/-/g, '.')
  })

  useEffect(() => {
    if (initialData) {
      setFormData({
        title: initialData.title,
        content: initialData.content,
        author: initialData.author,
        isHandwritten: initialData.isHandwritten,
        date: initialData.date
      })
    } else {
      setFormData({
        title: '',
        content: '',
        author: '他',
        isHandwritten: false,
        date: formatDate().replace(/-/g, '.')
      })
    }
  }, [initialData, isOpen])

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault()
    if (!formData.title.trim() || !formData.content.trim()) {
      alert('请填写标题和内容')
      return
    }

    if (initialData) {
      onSubmit({
        ...initialData,
        ...formData
      })
    } else {
      onSubmit(formData)
    }
  }

  return (
    <AnimatePresence>
      {isOpen && (
        <motion.div
          className="fixed inset-0 bg-black/50 backdrop-blur-sm z-50 flex items-center justify-center p-4"
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          exit={{ opacity: 0 }}
          onClick={onClose}
        >
          <motion.div
            className="bg-white rounded-3xl p-8 max-w-3xl w-full max-h-[90vh] overflow-y-auto"
            initial={{ scale: 0.8, opacity: 0 }}
            animate={{ scale: 1, opacity: 1 }}
            exit={{ scale: 0.8, opacity: 0 }}
            onClick={(e) => e.stopPropagation()}
          >
            <div className="flex items-center justify-between mb-6">
              <h2 className="text-2xl font-bold text-gray-800">
                {initialData ? '编辑情书' : '写一封新情书'} 💌
              </h2>
              <button
                onClick={onClose}
                className="text-gray-400 hover:text-gray-600 text-2xl"
              >
                ✕
              </button>
            </div>

            <form onSubmit={handleSubmit} className="space-y-6">
              {/* 标题 */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  标题 *
                </label>
                <input
                  type="text"
                  value={formData.title}
                  onChange={(e) => setFormData(prev => ({ ...prev, title: e.target.value }))}
                  className="w-full px-4 py-3 border border-gray-300 rounded-xl focus:outline-none focus:ring-2 focus:ring-rose-400"
                  placeholder="给这封情书起个标题..."
                  required
                />
              </div>

              {/* 日期和作者 */}
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    日期
                  </label>
                  <input
                    type="text"
                    value={formData.date}
                    onChange={(e) => setFormData(prev => ({ ...prev, date: e.target.value }))}
                    className="w-full px-4 py-3 border border-gray-300 rounded-xl focus:outline-none focus:ring-2 focus:ring-rose-400"
                    placeholder="2024.02.14"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    作者
                  </label>
                  <select
                    value={formData.author}
                    onChange={(e) => setFormData(prev => ({ ...prev, author: e.target.value }))}
                    className="w-full px-4 py-3 border border-gray-300 rounded-xl focus:outline-none focus:ring-2 focus:ring-rose-400"
                  >
                    <option value="他">他</option>
                    <option value="她">她</option>
                  </select>
                </div>
              </div>

              {/* 手写选项 */}
              <div>
                <label className="flex items-center space-x-3 cursor-pointer">
                  <input
                    type="checkbox"
                    checked={formData.isHandwritten}
                    onChange={(e) => setFormData(prev => ({ ...prev, isHandwritten: e.target.checked }))}
                    className="w-5 h-5 text-rose-500 rounded focus:ring-rose-400"
                  />
                  <span className="text-gray-700">这是手写原稿 ✍️</span>
                </label>
              </div>

              {/* 内容 */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  内容 *
                </label>
                <textarea
                  value={formData.content}
                  onChange={(e) => setFormData(prev => ({ ...prev, content: e.target.value }))}
                  className="w-full px-4 py-3 border border-gray-300 rounded-xl focus:outline-none focus:ring-2 focus:ring-rose-400 resize-none"
                  rows={8}
                  placeholder="在这里写下你想说的话...&#10;&#10;可以用换行来分段，让情书更有层次感。"
                  required
                />
                <p className="text-xs text-gray-500 mt-1">
                  💡 提示：使用换行可以让情书更有层次感
                </p>
              </div>

              {/* 提交按钮 */}
              <div className="flex space-x-4 pt-4">
                <button
                  type="button"
                  onClick={onClose}
                  className="flex-1 px-6 py-3 border border-gray-300 text-gray-700 rounded-xl hover:bg-gray-50 transition-colors"
                >
                  取消
                </button>
                <button
                  type="submit"
                  className="flex-1 px-6 py-3 bg-gradient-to-r from-rose-500 to-pink-500 text-white rounded-xl hover:from-rose-600 hover:to-pink-600 transition-all"
                >
                  {initialData ? '保存修改' : '保存情书'} 💕
                </button>
              </div>
            </form>
          </motion.div>
        </motion.div>
      )}
    </AnimatePresence>
  )
}
